package com.shaozi.nc.quartz.crm;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.util.ReflectionUtils;

import com.shaozi.data.mq.business.base.MqConsts.UserType;
import com.shaozi.data.mq.business.base.SourceTypeConsts.OA.Crm_Sale;
import com.shaozi.data.mq.business.bean.MqTargetUserBean;
import com.shaozi.data.mq.business.utils.MqUtil;
import com.shaozi.im.protocol.core.IMConsts;
import com.shaozi.lib.throwable.SzException;
import com.shaozi.nc.data.hibVO.CrmPipelineVO;
import com.shaozi.nc.data.model.SecretaryModel;
import com.shaozi.nc.hibservice.CrmCustomerService;
import com.shaozi.nc.hibservice.CrmOpenSeeRuleService;
import com.shaozi.nc.mq.bean.crm.OpenSeeRecoverExtraBean;
import com.shaozi.nc.quartz.crm.pojo.OpenSeeRulePipelinePojo;
import com.shaozi.nc.quartz.crm.pojo.UserCountPojo;
import com.shaozi.nc.utils.SecretaryHelper;
import com.shaozi.utils.common.SysUtils;
import com.shaozi.utils.spel.SimpleEval;

/**
 * CRM公海客户收回预提醒
 * 
 * @author brenx
 *
 */
public class CrmSaleOpenSeeRecoverExecute extends CrmOpenSeeBaseExecute {

	private Logger logger = Logger.getLogger(CrmSaleOpenSeeRecoverExecute.class);

	private String title, content;

	public CrmSaleOpenSeeRecoverExecute() {
		title = beanUtils.getConfig().getValue("push.msg.oa.crm.title");
		content = beanUtils.getConfig().getValue("push.msg.oa.crm.openSee.customer.will.recover.batch");

		noBackGroupByUserMethods.put(BackType_Activity, "noActivityBackGroupByUser");
		noBackGroupByUserMethods.put(BackType_Order, "noOrderBackGroupByUser");

		noBackMethods.put(BackType_Activity, "noActivityBack");
		noBackMethods.put(BackType_Order, "noOrderBack");
	}

	@Override
	protected void scheduleGroupByUser(String companyId, int backType, final List<UserCountPojo> userTotalCounts,
			long key) throws SzException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		userCounts(companyId, backType, userTotalCounts, key);
	}

	@SuppressWarnings("unchecked")
	private void userCounts(String companyId, int backType, final List<UserCountPojo> userTotalCounts,
			long keyTimeStamp)
			throws SzException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		final String methodName = noBackMethods.get(backType);
		Method serviceMethod = ReflectionUtils.findMethod(CrmOpenSeeRuleService.class, methodName, String.class,
				List.class);

		List<Integer> debugPipelineIds = null;
		List<OpenSeeRulePipelinePojo> ruleVos = (List<OpenSeeRulePipelinePojo>) serviceMethod
				.invoke(crmOpenSeeRuleService, companyId, debugPipelineIds);
		if (ruleVos.isEmpty())
			return;
		List<Integer> pipelineIds = SysUtils.getArrayFieldVals(ruleVos, "pipelineId");
		if (pipelineIds.isEmpty())
			return;
		List<Integer> stageIds = crmPipelineStageService.getStageIds(pipelineIds);

		if (!ruleVos.isEmpty()) {
			saveToOpenseaCustomer(companyId, backType, ruleVos, stageIds, Type_Recover, userTotalCounts, keyTimeStamp,false);
		}

		final Method method = ReflectionUtils.findMethod(CrmCustomerService.class,
				noBackGroupByUserMethods.get(backType), String.class, OpenSeeRulePipelinePojo.class, List.class);
		ruleVos.forEach(ruleVo -> {
			try {
				List<UserCountPojo> pojos = (List<UserCountPojo>) method.invoke(crmCustomerService, companyId, ruleVo,
						stageIds);
				pojos.forEach(userCount -> {
					String key = getUniqueKey(userCount.getPipelineId(), userCount.getUserId());
					if (!uniquePipelineIds.containsKey(key)) {
						uniquePipelineIds.put(key, userCount);
						userTotalCounts.add(userCount);
					} else {
						UserCountPojo pojo = uniquePipelineIds.get(key);
						pojo.getCustomerIds().putAll(userCount.getCustomerIds());
					}
				});
			} catch (Exception e) {
				logger.error(SzException.getStackMessage(e));
			}
		});
	}

	@Override
	protected List<SecretaryModel> getSecretaryModes(String companyId, int backType, int userId, int pipelineId,
			long counts, long key) throws SzException {
		final int type = 0;
		List<SecretaryModel> ret = new ArrayList<>();
		int sourceType = Crm_Sale.OpenSee_Customer_Will_Recover;
		SimpleEval eval = new SimpleEval();
		List<MqTargetUserBean> users = new ArrayList<>();
		MqTargetUserBean user = new MqTargetUserBean(String.valueOf(userId));
		users.add(user);

		SecretaryModel secretary = new SecretaryModel();
		secretary.setSourceType(sourceType);
		secretary.setPushType(SecretaryModel.PushType_Need_Save);
		secretary.setUsers(users);
		secretary.setCompanyId(companyId);
		secretary.setTriggerUserId(String.valueOf(IMConsts.SysMemberId.Secretary_Id));
		secretary.setFromUserId(String.valueOf(IMConsts.SysMemberId.Secretary_Id));
		secretary.setTitle(title);
		Map<String, Object> params = new HashMap<>();
		params.put("counts", counts);
		// params.put("backTypeTitle", getBackTypeTitle(backType));
		params.put("customType", getCustomTypeTitle(type));
		params.put("customerName", "");
		CrmPipelineVO pipelineVo = crmPipelineService.findOne(pipelineId);
		if (pipelineVo == null) {
			logger.warn("pipelineid=" + pipelineId + " get null");
			return null;
		}
		params.put("productName", pipelineVo == null ? "" : pipelineVo.getName());

		String c = (String) eval.eval(content, params);
		secretary.setContent(c);

		secretary.setType(MqUtil.getBaseSourceType(sourceType));
		secretary.setNotifyType(SecretaryHelper.getNotifyTypeFromSourceType(sourceType, UserType.Undefine));
		OpenSeeRecoverExtraBean extra = new OpenSeeRecoverExtraBean(null);
		extra.setType(type);
		extra.setIsMulti(1);
		extra.setPipelineId(pipelineId);
		extra.setKey(getKey(key, backType));
		secretary.setExtra(extra.toJsonString());
		secretary.setExtraBean(extra);
		ret.add(secretary);
		return ret;
	}

}
